import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { PAGE_COUNT } from '../../../app/app.constants';
import { ApiProvider } from '../../../providers/api/api';
import { NotificationProvider } from '../../../providers/notification/notification';
import { ZBar, ZBarOptions } from '@ionic-native/zbar';

/**
 * Generated class for the ScanDetailPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-scan-detail',
  templateUrl: 'scan-detail.html',
})
export class ScanDetailPage {
  slides: string[] = ['未盘(0)', '正常(0)', '盘盈(0)', '盘亏(0)'];//显示的数据
  pageNumber: number = 4;//同时显示的个数
  selectedIndex: number = 0;//默认选中的
  nores: boolean = true; //当前项是否无数据

  private scanId: string;
  private showBox = false;
  private curItem;  //当前选中记录
  private curnum: number; //当前物资库存
  private scannum: number;  //当前物资实际数量
  private funid = 'sp_scan_ansdet';
  private items: Array<string>; //选中项
  private item1: Array<string> = []; //未盘 
  private item2: Array<string> = []; //正常
  private item3: Array<string> = []; //盘盈
  private item4: Array<string> = []; //盘亏
  private searchValue: string;
  private options = {
    where_sql: 'sp_scan_det.scan_id=?',
    where_type: 'string',
    where_value: ''
  };

  constructor(public navCtrl: NavController,
    public navParams: NavParams,
    public api: ApiProvider,
    public notification: NotificationProvider,
    private zbar: ZBar) {
    this.scanId = navParams.get('scan_id');
    this.options.where_value = this.scanId;
    this.notification.showLoading();
    let res = this.api.getList(this.funid, this.options).subscribe(res => {
      if (res['success']) {
        let allItems = res['data']['root'];
        allItems.forEach(item => {
          let scan_result = item.sp_scan_det__scan_result;
          switch (scan_result) {
            case '正常': this.item2.push(item); break;
            case '盘盈': this.item3.push(item); break;
            case '盘亏': this.item4.push(item); break;
            default: this.item1.push(item);
          }
        });
        this.updateSlides();
        this.items = this.item1;
        if (!this.item1 || this.item1.length == 0) this.nores = true;
        else this.nores = false;
      } else {
        this.notification.showAlert(res['message']);
      }
      this.notification.hideLoading();
    })
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ScanDetailPage');
  }

  selTab(i, slide) {
    if (this.selectedIndex == i) return;
    this.selectedIndex = i;
    switch (i) {
      case 0: this.items = this.item1; break;
      case 1: this.items = this.item2; break;
      case 2: this.items = this.item3; break;
      case 3: this.items = this.item4; break;
      default: this.items = this.item1;
    }

    this.nores = this.items.length == 0 ? true : false;
  }

  selItem(item) {
    //if(item.sp_scan_det__scan_result=='正常'||item.sp_scan_det__scan_result=='盘盈'||item.sp_scan_det__scan_result=='盘亏') return;
    this.curItem = item;
    this.curnum = item.sp_scan_det__store_num;
    this.scannum = Number(parseInt(item.sp_scan_det__store_num).toFixed(2));
    this.showBox = true;
  }

  cancelRes() {
    this.showBox = false;
  }

  confirmRes() {
    let scannum = this.scannum;
    if (!scannum) {
      this.notification.showAlert("盘点数量不能为空！");
      return;
    }
    let params = {
      funid: 'sp_scan_ansdet',
      eventcode: 'scanres',
      scan_det_id: this.curItem.sp_scan_det__scan_det_id,
      scan_num: scannum
    }
    this.api.request(params).subscribe(res => {
      if (res['success']) {
        this.item1.splice(this.curItem);

        if (scannum - this.curnum == 0) {
          this.item2.unshift(this.curItem);
        } else if (scannum - this.curnum > 0) {
          this.item3.unshift(this.curItem);
        } else if (scannum - this.curnum > 0) {
          this.item4.unshift(this.curItem);
        }
        if (!this.item1 || this.item1.length == 0) this.nores = true;
        this.updateSlides();
      }
      this.showBox = false;
      this.scannum = 0;
    });

  }

  /**
   * 更新项目数量
   */
  updateSlides() {
    this.slides[0] = '未盘(' + this.item1.length + ')';
    this.slides[1] = '正常(' + this.item2.length + ')';
    this.slides[2] = '盘盈(' + this.item3.length + ')';
    this.slides[3] = '盘亏(' + this.item4.length + ')';
  }

  /**
   * 扫码
   */
  scan() {
    let isExist = false;

    let options: ZBarOptions = {
      flash: 'off',
      text_title: '二维码扫描',
      text_instructions: '请将镜头对准二维码',
      drawSight: false
    };

    this.zbar.scan(options)
      .then(result => {
        //alert("结果：" + result); // Scanned code
        let isExist = false;
        this.item1.forEach(item => {
          if (result == item['sp_scan_det__sp_code']) {
            isExist = true;
            this.selItem(item);
            return;
          }
        });
        if (!isExist) this.notification.showToast('该货品已盘点或不存在此任务');
      })
  }

  /**
   * 盘点结果提交
   */
  commit() {
    //提示确认
    let params = {
      funid: 'sp_scan_ansdet',
      eventcode: 'scanok',
      scanid: this.scanId,
    }
    this.notification.showConfirm('提示', '是否提交盘点结果？', res => {
      if (res == 0) return;
      let params = {};
      this.api.request(params).subscribe(res => {
        if (res['success']) {
          this.notification.showToast("盘点结果已提交");
          this.navCtrl.pop();
        } else {
          this.notification.showToast(res['message']);
          return;
        }
      })
    })

  }


}
